package com.nowcoder.code.hjnc;

import java.util.*;

public class NC97 {

    public String[][] topKstrings(String[] strings, int k) {

        HashMap<String, Integer> map = new HashMap<>();

        for (String string : strings) {
            map.put(string, map.getOrDefault(string, 0) + 1);
        }

        PriorityQueue<Map.Entry<String, Integer>> priorityQueue = new PriorityQueue<>(k, (o1, o2) -> {
            if (o1.getValue() > o2.getValue()) {
                return 1;
            } else if (o1.getValue() < o2.getValue()) {
                return -1;
            }
            return -o1.getKey().compareTo(o2.getKey());
        });

        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            priorityQueue.add(entry);
            if (priorityQueue.size() > k) {
                priorityQueue.poll();
            }
        }

        String[][] ss = new String[k][2];
        for (int i = k - 1; i >= 0; i--) {
            Map.Entry<String, Integer> entry = priorityQueue.poll();
            ss[i][0] = entry.getKey();
            ss[i][1] = entry.getValue().toString();
        }
        return ss;
    }

    public static void main(String[] args) {
        String[] ss = {"a","b","c","b"};
        System.out.println(Arrays.deepToString(new NC97().topKstrings(ss, 2)));
    }

}
